The URL of the originally requested file is stored in
the ReturnURL key of
the query string. This is part of the job of the ASP.NET
framework. Say, for example, that an unlogged-in user
navigates to the following page:
http://security/members/MemberOnlyFile.aspx
Because the user isn't logged in, the login page
appears (note the query string that's automatically
attached for you):
http://security/login.aspx?ReturnUrl=%2fmembers%2fMemberOnlyFile.aspx
So long as the user enters appropriate login
credentials, the page redirects her or him automatically
to the MemberOnlyFile.aspx file in the members
folder.
Put it all together now. The code snippet
from login.aspx in Listing 4 shows the code that replaces
the call to FormsAuthentication.RedirectFromLoginPage .
The managerLogin.aspx Page
The whole reason for adding roles is so
that you could establish a manager with
its own login and set of protected pages.
Look at managerLogin.aspx (in the root
of the site), as annotated in Listing 5.
As you read through the code you'll notice
similarities to the login.aspx page. One
new concept is detecting whether the user
is already logged in. The version of the
login.aspx file that you've worked on
so far doesn't exhibit this feature but
probably should. (Also see "Determine if the user
is already logged in" for more info.)
I've already discussed the changes necessary
in the web.config file. (See the earlier
section "Create multiple roles in
the web.config file.") In addition
to the manager's login page and modifications
to web.config, role-based authentication
requires event handling for OnAuthenticateRequest in Global.asax.
Handling the
OnAuthenticateRequest Event in
Global.asax The OnAuthenticateRequest event is
raised whenever a user navigates to a page in a folder
that is protected by Forms authentication. Before you
added the complexity of multiple roles this event was
handled automatically for you by the ASP.NET framework.
However, now you need to deal with it explicitly.
Global.asax, the ASP.NET application
file, is an optional file that contains
code for responding to application-level
events raised by ASP.NET or by HTTP modules.
You're going to add a section to handle
the OnAuthenticateRequest
event (see Listing 6).
When a page in the protected (members or manager)
folder is requested, the ASP.NET framework automatically
executes this method because the OnAuthenticateRequest event is
raised. The first check is whether or not the user even
exists. If the user does exist, is he or she
authenticated (that is, does the user have a ticket)? If
yes, get the ticket associated with this user and then
get the userData value stored in the ticket and extract
the list of roles. Finally, create a new GenericPrincipal using the current
user's forms identity and roles. |